package org.jie.guider.framework.springboot;

import java.util.concurrent.TimeUnit;
import org.jie.guider.framework.springboot.kafka.ChannelMessageListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.config.KafkaListenerEndpointRegistry;
import org.springframework.kafka.core.KafkaOperations;
import org.springframework.kafka.listener.MessageListenerContainer;
import org.springframework.stereotype.Component;

/**
 * @author LiJie
 */
@Component
public class ShutdownHookService {
    private static final Logger LOG =
        LoggerFactory.getLogger(ShutdownHookService.class);

    @Autowired
    private KafkaListenerEndpointRegistry kafkaListenerRegistry;
    @Autowired
    private KafkaOperations<String, String> kafkaOperations;

    public void shutdown() {
        LOG.info("即将关闭服务");
        ChannelMessageListener.pool.shutdown();
        try {
            if (!ChannelMessageListener.pool.pool.awaitTermination(30L, TimeUnit.SECONDS)) {
                LOG.warn("Timed out while waiting for executor");
            }
        } catch (InterruptedException e) {
            LOG.warn("Interrupted while waiting for executor to terminate");
        }
//        try {
//            TimeUnit.MINUTES.sleep(1);
//        } catch (InterruptedException ignore) {
//        }
        LOG.info("服务关闭完成");
    }

    private void kafkaConsumerShutdown() {
        for (MessageListenerContainer container : kafkaListenerRegistry.getListenerContainers()) {
            container.stop();
        }
        kafkaListenerRegistry.stop();
    }
}
